import { onBeforeUnmount, ref, type Ref } from 'vue'

import elementResizeDetector from 'element-resize-detector'
import { debounce } from 'lodash-es'
import type { ECharts } from 'echarts'
import type { ECBasicOption } from 'echarts/types/dist/shared'
import * as echarts from 'echarts'

/**
 *
 * @param {*} refs 图表渲染元素
 * @param {*} options 图表参数
 * @param {*} animationDuration 动画时长 会覆盖 options中的
 * @param {*} animationDurationUpdate 更新动画时长 会覆盖 options中的
 * @returns
 */
export default function useChart(
  refs: Ref<HTMLDivElement | undefined>,
  options: ECBasicOption,
  animationDuration: number = 100,
  animationDurationUpdate: number = 500
) {
  if (!refs.value) return
  const chartInst = echarts.init(refs.value)
  const chartRef = ref<ECharts>()
  const erd = elementResizeDetector()
  /**
   * 使用到 lodash 防抖函数
   * 定义 resize 事件
   */
  const handleResize = debounce(() => {
    chartInst.resize()
  })

  // chartInst = echarts.init(refs.value)
  chartInst.setOption({
    ...options,
    animationDuration,
    animationDurationUpdate
  })
  chartRef.value = chartInst
  // window.addEventListener('resize', handleResize)
  setTimeout(() => {
    try {
      if (!refs.value) return
      erd.listenTo(refs.value, handleResize)
    } catch (_) {
      //
    }
  }, animationDuration)
  onBeforeUnmount(() => {
    chartInst?.dispose()
    if (!refs.value) return
    erd.removeListener(refs.value, handleResize)
  })
  return chartRef
}
